package top.wecreate.view;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public abstract class HandlerTimer {
	private static final String TAG = HandlerTimer.class.getSimpleName();

	private int WHAT_TICK_TIMER = 0;
	private int WHAT_FINISH_TIMER = 1;

	private int mTickMills;
	private int mFinishMills;

	private Handler handlerTimer;

	public HandlerTimer(int tickMills, int finishMills) {
		mTickMills = tickMills;
		mFinishMills = finishMills;

		handlerTimer = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				int what = msg.what;
				if (what == WHAT_TICK_TIMER) {
					Log.d(TAG, "WHAT_TICK_TIMER");
					onTick();
					handlerTimer.sendEmptyMessageDelayed(WHAT_FINISH_TIMER,
							mFinishMills);
				} else if (what == WHAT_FINISH_TIMER) {
					onFinish();
					if (!needCancel) {
						// 起到一直监听的作用
						start();
					}
				}
			}
		};
	}

	public void setTickMills(int mills) {
		mTickMills = mills;
		cancel();
		start();
	}

	public void start() {
		needCancel = false;

		if (!handlerTimer.hasMessages(WHAT_TICK_TIMER)) {
			handlerTimer.sendEmptyMessageDelayed(WHAT_TICK_TIMER, mTickMills);
		} else {
		}
	}

	private boolean needCancel = false;

	public void cancel() {

		Log.e("TAG", "!!!!   cancel   !!!");
		StackTraceElement[] elements = Thread.currentThread().getStackTrace();
		for(StackTraceElement ele:elements)
		{
		     Log.i("TAG",ele.toString());
		}
		needCancel = true;
		handlerTimer.removeMessages(WHAT_TICK_TIMER);
		handlerTimer.removeMessages(WHAT_FINISH_TIMER);
	}

	public abstract void onTick();

	public abstract void onFinish();
}
